package cn.cosmosx.base.handler;

import cn.cosmosx.base.constant.ResultCode;
import cn.cosmosx.base.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import cn.cosmosx.base.define.ResultVO;

import javax.servlet.ServletException;
import javax.validation.ConstraintViolationException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;

/**
 * 系统全局异常处理，统一异常拦截处理
 *
 * @author gengzhy
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    public static final String DEFAULT_ERROR_CODE = "E";
    private static final String DEFAULT_ERROR_MSG = "网络繁忙,请稍后再试";

    // 自定义的校验注解
    private final static Set<String> CUSTOMER_VALID_ANNOTATION = new HashSet<>();

    /**
     * 捕获{@code BaseException}类型的异常
     */
    @ExceptionHandler(BaseException.class)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.OK)
    public ResultVO<?> handleBaseException(BaseException ex) {
        return ResultVO.failed(ex.getResultCode(), ex.getMessage());
    }

    /**
     * 捕获{@code @RequestBody} 参数校验不通过时抛出的异常处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.OK)
    public ResultVO<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder msg = new StringBuilder();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            String annName = fieldError.getCode();
            if (!CUSTOMER_VALID_ANNOTATION.contains(annName)) {
                msg.append("[").append(fieldError.getField()).append("]");
            }
            msg.append(fieldError.getDefaultMessage()).append(" ");
        }
        return ResultVO.failed(ResultCode.P00002, msg.toString());
    }

    /**
     * 捕获@code @PathVariable} 和 {@code @RequestParam} 参数校验不通过时抛出的异常处理
     */
    @ExceptionHandler({ConstraintViolationException.class, ServletException.class})
    @ResponseBody
    @ResponseStatus(value = HttpStatus.OK)
    public ResultVO<?> handleConstraintViolationException(Exception ex) {
        log.error("请求方式异常", ex);
        if (ex instanceof ConstraintViolationException) {
            ConstraintViolationException e = (ConstraintViolationException) ex;
            return ResultVO.failed(ResultCode.P00000, e.getMessage());
        }
        // 文件为空
        if (ex instanceof MissingServletRequestPartException) {
            MissingServletRequestPartException e = (MissingServletRequestPartException) ex;
            String message = String.format("[%s]参数不能为空", e.getRequestPartName());
            return ResultVO.failed(ResultCode.P00000, message);
        }
        // 请求方式异常
        if (ex instanceof HttpRequestMethodNotSupportedException) {
            HttpRequestMethodNotSupportedException e = (HttpRequestMethodNotSupportedException) ex;
            List<String> supportMethods = Arrays.asList(Optional.ofNullable(e.getSupportedMethods()).orElse(new String[0]));
            String message = String.format("不支持[%s]请求方式，仅支持%s", e.getMethod(), supportMethods);
            return ResultVO.failed(ResultCode.B00000, message);
        }
        // 参数错误
        if (ex instanceof MissingServletRequestParameterException) {
            MissingServletRequestParameterException e = (MissingServletRequestParameterException) ex;
            String message = String.format("[%s]不能为空", e.getParameterName());
            return ResultVO.failed(ResultCode.B00000, message);
        }
        return ResultVO.failed(ResultCode.E, DEFAULT_ERROR_MSG);
    }

    /**
     * 参数格式异常处理
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.OK)
    public ResultVO<?> handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) {
        String message = ex.getMessage();
        log.error("参数格式错误:{}", message, ex);
        return ResultVO.failed(ResultCode.P00004);
    }

    /**
     * 参数格式异常处理
     *
     * @param ex
     * @return
     */
    @ExceptionHandler({IllegalStateException.class})
    @ResponseBody
    @ResponseStatus(value = HttpStatus.OK)
    public ResultVO<?> handleIllegalStateException(IllegalStateException ex) {
        Throwable cause;
        String message = null;
        if ((cause = ex.getCause()) != null) {
            message = cause.getMessage();
        }
        message = message == null ? ex.getMessage() : message;
        log.error("请求异常:{}", message, ex);
        return ResultVO.failed(ResultCode.B00000, message);
    }

    /**
     * 其它异常处理（针对普通请求和JSON格式）
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.OK)
    public ModelAndView handleException(Exception ex, HandlerMethod handle) {
        // 打印堆栈信息
        PrintWriter writer = new PrintWriter(new StringWriter());
        ex.printStackTrace(writer);
        if (handle.getBean().getClass().isAnnotationPresent(RestController.class)
                || handle.hasMethodAnnotation(ResponseBody.class)) {
            ModelAndView mv = new ModelAndView(new MappingJackson2JsonView());
            mv.addObject("code", DEFAULT_ERROR_CODE);
            mv.addObject("message", DEFAULT_ERROR_MSG);
            mv.addObject("data", null);
            return mv;
        }
        ModelAndView mv = new ModelAndView("error/error", HttpStatus.OK);
        mv.addObject("code", DEFAULT_ERROR_CODE);
        mv.addObject("message", DEFAULT_ERROR_MSG);
        return mv;
    }

}
